﻿<%@ WebHandler Language="C#" Class="_7_验证码" %>

using System;
using System.Web;

public class _7_验证码 : IHttpHandler,System.Web.SessionState.IRequiresSessionState {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "image/JPEG";
       // string checkCode = "孤灯人影";
        Random randomNumber = new Random();
        int checkNumber = randomNumber.Next(1000, 9999);
        string checkNumberStr = checkNumber.ToString();
        HttpContext.Current.Session["code"] = checkNumberStr;
        //创建画板，（宽，高）
        using(System.Drawing.Bitmap image = new System.Drawing.Bitmap(50,22))
        {
            using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(image))
            {
                Random random = new Random();//生成随机生成器
                g.Clear(System.Drawing.Color.White);//清空图片背景色
                //画图片的背景噪音线
                for (int i = 0; i < 2; i++)
                {
                    int x1 = random.Next(image.Width);
                    int x2 = random.Next(image.Width);
                    int y1 = random.Next(image.Height);
                    int y2 = random.Next(image.Height);
                    g.DrawLine(new System.Drawing.Pen(System.Drawing.Color.Black), x1, y1, x2, y2);
                }
                System.Drawing.Font font = new System.Drawing.Font("Arial", 12, (System.Drawing.FontStyle.Bold));
                System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(
                    new System.Drawing.Rectangle(0, 0, image.Width, image.Height), System.Drawing.Color.Blue, System.Drawing.Color.DarkRed,
                    1.2f, true);
                g.DrawString(checkNumberStr, font, brush, 2, 2);
                //画图片的前景噪音线
                for (int i = 0; i < 100; i++)
                {
                    int x = random.Next(image.Width);
                    int y = random.Next(image.Height);
                    image.SetPixel(x,y,System.Drawing.Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new System.Drawing.Pen(System.Drawing.Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
               // System.IO.MemoryStream ms = new System.IO.MemoryStream();
               // image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                image.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }


    #region IDisposable 成员

    public void Dispose()
    {
        throw new NotImplementedException();
    }

    #endregion
}